$(function() {
    //主流程对象
    var mainCtrl = avalon.define({
        $id: "mainController",
        searchCommCode : "",
        commCode: "",
        mertCode: "",
        partName: "",
        price: "",
        pic : "",
        cateCode : "1001",
        typeId : "10",
        beginDate: getMinDate(0) + " 00:00:00",
        endDate: getMinDate(30) + " 00:00:00",
        allCategory: [],
        initMain: function(){
        	mainCtrl.searchCommCode = "";
        	mainCtrl.commCode = "";
        	mainCtrl.mertCode = "";
        	mainCtrl.partName = "";
        	mainCtrl.price = "";
        	mainCtrl.pic = "";
        	mainCtrl.cateCode = "1001";
        	mainCtrl.typeId = "10";
        	mainCtrl.beginDate = getMinDate(0) + " 00:00:00";
        	mainCtrl.endDate = getMinDate(30) + " 00:00:00";
        },
        queryAllCategory: function() {
            $.ajax({
                type: "post",
                dataType: "json",
                url: DI.queryMssCateList,
                success: function(data) {
                    mainCtrl.allCategory = data.data.list;
                }
            });
        },
        getUrl: function(commcode) {
            var codeLen = commcode.length;
            if (codeLen == 18) {
                return DI.imageSplitURL + commcode + "_1_100x100.jpg";
            } else {
                var curLen = 18 - codeLen,
                    curZero = "";
                for (var i = 0; i < curLen; i++) {
                    curZero += "0";
                }
                return DI.imageSplitURL + curZero + "" + commcode + "_1_100x100.jpg";
            }
            return "";
        },
        processName: function(name) {
        	if (typeof name != "undefined" && name != null && name.length >15) {
        		return name.substring(0, 12) + "...";
        	}
        	return name;
        },
        queryPrice: function(commCode, mertCode) {
        	var url = DI.getMssPrice;
        	// 置换URL
        	url = url.replace("{cmmdtyCode}", commCode);
        	url = url.replace("{bizCode}", mertCode);
        	// 查询价格
        	$.ajax({
                type: "GET",
                dataType: "jsonp",
                url: url,
                jsonp: false,
                jsonpCallback:"priceBack",
                success: function(data) {
                	var price = data[0].price;
                	if (typeof price == "undefined" || price == "" || price == null) {
                		mainCtrl.price = "售罄";
                	} else {
                		mainCtrl.price = price;
                	}
                },
                error: function(err) {
                    console.log(err)
                }
            });
        },
        initCommCode:function(commCode) {
        	var cc = commCode;
        	if (typeof cc != "undefined") {
        		// 18位
        		cc = "000000000000000000" + cc;
        		return cc.substring(cc.length-18, cc.length);
        	}
        	return commCode;
        },
        initMertCode:function(mertCode) {
        	var mc = mertCode;
        	if (typeof mc == "undefined" || mc == "0" || mc == null || mc.length != 10) {
        		// 10位0-自营
        		return "0000000000";
        	}
        	return mertCode;
        },
        searchComm: function() {
        	var code = mainCtrl.searchCommCode;
        	if (code.length != 9 && code.length != 18) {
        		PLATFORM.showTips("warning", "请输入正确商品编码");
        		return;
        	}
        	var searchParam = {
                    "keyword": mainCtrl.searchCommCode, //关键词
                    "channelId": "MOBILE",//渠道
                    "st": 0,//默认排序（默认值）
                    "ct": -1,//-1：查全部商家商品,包括苏宁、C店, 2-苏宁自营
                    "ps": 1,//页面大小，即每页返回结果个数
                    "cp": 0,//当前页码，从第0页开始（可选）
                    "yuyue": -1,//预约商品筛选 -1：返回所有
                    "set": 5,//5 手机混排
                    "cityId": 9173,//城市id
                    "iv": -1,//是否有货（可选） -1 全部
                    "unsale": 1, //1：展示暂不销售,
                    "isTiled": 1 //1：为平铺 返回商家编码
                }
        	$.ajax({
                type: "get",
                dataType: "jsonp",
                jsonpCallback:"callback",
                data: searchParam,
                url: DI.mobileSearch,
                success: function(data) {
                	var total = data.goodsCount;
                	if (typeof total != "undefined" && total >= 1) {
                		var goods = data.goods;
                		mainCtrl.commCode = goods[0].partnumber;
                    	mainCtrl.partName = goods[0].catentdesc;
                    	mainCtrl.mertCode = mainCtrl.initMertCode(goods[0].salesCode);
                    	mainCtrl.queryPrice(mainCtrl.initCommCode(mainCtrl.commCode), 
                    			mainCtrl.mertCode);
                    	mainCtrl.pic = mainCtrl.getUrl(mainCtrl.initCommCode(mainCtrl.commCode));
                    	$("#commBody").show();
                	} else {
                		$("#commBody").hide();
                		PLATFORM.showTips("warning", "未搜索到商品信息");
                		mainCtrl.commCode = "";
                    	mainCtrl.partName = "";
                    	mainCtrl.mertCode = "";
                    	mainCtrl.price = "";
                	}
                },
                error: function(err) {
                    console.log(err)
                }
            });
        },
        addComm: function() {
        	var saveParam = {
                commCode: mainCtrl.commCode,
                mertCode: mainCtrl.mertCode,
                cateCode : mainCtrl.cateCode,
                typeId : mainCtrl.typeId,
                beginDate: mainCtrl.beginDate,
                endDate: mainCtrl.endDate,
            }
        	if ("" == mainCtrl.commCode) {
        		PLATFORM.showTips("warning", "商品编码为空,无法保存");
        		return;
        	}
        	if ("" == mainCtrl.mertCode) {
        		PLATFORM.showTips("warning", "商家编码为空,无法保存");
        		return;
        	}
        	if ("" == mainCtrl.cateCode) {
        		PLATFORM.showTips("warning", "品类编码为空,无法保存");
        		return;
        	}
        	if ("" == mainCtrl.typeId) {
        		PLATFORM.showTips("warning", "类型编码为空,无法保存");
        		return;
        	}
        	if ("" == mainCtrl.beginDate) {
        		PLATFORM.showTips("warning", "开始时间为空,无法保存");
        		return;
        	}
        	if ("" == mainCtrl.endDate) {
        		PLATFORM.showTips("warning", "结束时间为空,无法保存");
        		return;
        	}
        	$.ajax({
                type: "post",
                dataType: "json",
                data: saveParam,
                url: DI.saveMssComm,
                success: function(data) {
                	if(data.retFlag == 1) {
                        PLATFORM.showTips("success", "保存成功");
                        mainCtrl.initMain();
                        $("#commBody").hide();
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                },
                error: function(err) {
                    console.log(err)
                }
            });
        },
        back: function() {
        	window.location = "mssCommManage.html";
        }
    });
    
    var popCtrl = avalon.define({
        $id: "popController",
        confirmType: "del",
        delCommObj: "",
        confirmSure: function() {
            var dataJson = {
                "id": popCtrl.delCommObj.id + ""
            };
            $.ajax({
                type: "post",
                dataType: "json",
                data: dataJson,
                url: DI.deleteMssCommById,
                success: function(data) {
                    $("#popup_confirm").hide();
                    if(data.retFlag == 1) {
                        PLATFORM.showTips("success", "删除成功");
                    } else {
                        PLATFORM.showTips("error", data.errorMessage);
                    }
                },
                error: function(err) {
                    console.log(err)
                }
            });
        }
    });
    $("#beginDate").datetimepicker({
        showSecond: true,
        timeFormat: 'hh:mm:ss',
        onClose: function(selectedDate) {
            $("#endDate").datepicker("option", "minDate", selectedDate);
        }
    });
    $("#endDate").datetimepicker({
        showSecond: true,
        timeFormat: 'hh:mm:ss',
        onClose: function(selectedDate) {
            $("#beginDate").datepicker("option", "maxDate", selectedDate);
        }
    });
    mainCtrl.queryAllCategory();
    $("#commBody").hide();
    // 初始化时间
    $("#endDate").datepicker("option", "minDate", mainCtrl.beginDate);
    $("#beginDate").datepicker("option", "maxDate", mainCtrl.endDate);
    $("#beginDate").datepicker("option", "minDate", mainCtrl.beginDate);
    avalon.scan();
});